// #ifdef H5
import WechatJSSDK from "@/plugin/jweixin-module/index.js";
import {BACK_URL, STATE_KEY} from '@/config/cache';

class AuthWechat {

  constructor() {
    this.instance = WechatJSSDK; // 微信实例化对象
    this.status = false; // 是否实例化
    this.initConfig = {};
  }

  // 获取经纬度；
  location() {

  }

  toPromise(fn, config = {}) {
    return new Promise((resolve, reject) => {
      fn({
        ...config,
        success(res) {
          resolve(res);
        },
        fail(err) {
          reject(err);
        },
        complete(err) {
          reject(err);
        },
        cancel(err) {
          reject(err);
        }
      });
    });
  }

  /**
   * 自动去授权
   */
  oAuthForMp() {

  }


  /**
   * 获取跳转授权后的地址
   * @param {Object} appId
   */
  getAuthUrl(appId, snsapiBase, backUrl) {
    let url = `${location.origin}${backUrl}`
    if (url.indexOf('?') === -1) {
      url = url + '?'
    } else {
      url = url + '&'
    }
    const redirect_uri = encodeURIComponent(
        `${url}scope=${snsapiBase}&back_url=` +
        encodeURIComponent(
            encodeURIComponent(
                uni.getStorageSync(BACK_URL) ? uni.getStorageSync(BACK_URL)
                    : location.pathname + location.search
            )
        )
    );
    uni.removeStorageSync(BACK_URL);
    const state = encodeURIComponent(
        ("" + Math.random()).split(".")[1] + "authorizestate"
    );
    uni.setStorageSync(STATE_KEY, state);
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${snsapiBase}&state=${state}#wechat_redirect`;
  }



  /**
   * 判断是否在微信公众号的浏览器中
   */
  isWeixin() {
    // 如果是 H5 环境
    if (typeof window !== "undefined" && window.navigator) {
      return navigator.userAgent.toLowerCase().includes("micromessenger");
    }

    // 如果是 uniapp 小程序环境
    // const systemInfo = uni.getSystemInfoSync();
    // return systemInfo.environment === "weixin";
    return false;
  }

}

export default new AuthWechat();
// #endif
